#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/stat.h>
#include "music.h"
#include "png.h"

extern int *lcd_ptr;

// 全局变量
static MusicFile *music_files = NULL;
static int music_count = 0;
static int current_music = 0;
static int current_page = 0;
static int music_per_page = 6;
static pid_t madplay_pid = -1;
static MusicState music_state = MUSIC_STOPPED;
static char current_playing[512] = "";

// 获取文件名（不含扩展名）
static char* get_filename_without_ext(const char *filename) {
    static char name[256];
    strcpy(name, filename);
    char *dot = strrchr(name, '.');
    if (dot) *dot = '\0';
    return name;
}

// 加载音乐封面
static int load_music_covers(MusicFile *files, int count) {
    for (int i = 0; i < count; i++) {
        char *name_without_ext = get_filename_without_ext(files[i].name);
        snprintf(files[i].cover_path, sizeof(files[i].cover_path), "/zdata/cover/%s.png", name_without_ext);
        
        struct stat st;
        files[i].has_cover = (stat(files[i].cover_path, &st) == 0);
    }
    return 0;
}

// 显示音乐封面
static int display_music_cover(const char *cover_path, int x, int y, int width, int height) {
    return cover_path ? lcd_draw_scale_png(cover_path, x, y, width, height) : -1;
}

// 绘制默认音乐背景
static void draw_default_music_bg(int x, int y, int width, int height) {
    for (int py = y; py < y + height; py++) {
        for (int px = x; px < x + width; px++) {
            if (px >= 0 && px < 800 && py >= 0 && py < 480) {
                lcd_ptr[py * 800 + px] = 0x333366;
            }
        }
    }
}

// 绘制播放状态边框
static void draw_playing_border(int x, int y, int width, int height) {
    for (int py = y - 2; py < y + height + 2; py++) {
        for (int px = x - 2; px < x + width + 2; px++) {
            if (px >= 0 && px < 800 && py >= 0 && py < 480) {
                if (py == y - 2 || py == y + height + 1 || px == x - 2 || px == x + width + 1) {
                    lcd_ptr[py * 800 + px] = 0x00FF00;
                }
            }
        }
    }
}

// 获取音乐文件列表
int get_music_files(MusicFile *files, int max_files) {
    DIR *dir = opendir("/zdata/music");
    if (!dir) return 0;
    
    struct dirent *entry;
    int count = 0;
    
    while ((entry = readdir(dir)) != NULL && count < max_files) {
        char *name = entry->d_name;
        char *ext = strrchr(name, '.');
        
        if (ext) {
            char lower_ext[10];
            strcpy(lower_ext, ext);
            for (int i = 0; lower_ext[i]; i++) {
                lower_ext[i] = tolower(lower_ext[i]);
            }
            
            if (strcmp(lower_ext, ".mp3") == 0 || 
                strcmp(lower_ext, ".wav") == 0 || 
                strcmp(lower_ext, ".ogg") == 0) {
                
                snprintf(files[count].path, sizeof(files[count].path), "/zdata/music/%s", name);
                strcpy(files[count].name, name);
                files[count].duration = 0;
                files[count].has_cover = 0;
                count++;
            }
        }
    }
    
    closedir(dir);
    if (count > 0) load_music_covers(files, count);
    return count;
}

// 播放音乐文件
int play_music(const char *file_path) {
    if (madplay_pid > 0) {
        kill(madplay_pid, SIGTERM);
        waitpid(madplay_pid, NULL, 0);
        madplay_pid = -1;
    }
    
    madplay_pid = fork();
    if (madplay_pid == 0) {
        execlp("madplay", "madplay", file_path, NULL);
        exit(1);
    } else if (madplay_pid > 0) {
        music_state = MUSIC_PLAYING;
        strcpy(current_playing, file_path);
        return 0;
    }
    return -1;
}

// 停止音乐播放
int stop_music(void) {
    if (madplay_pid > 0) {
        kill(madplay_pid, SIGTERM);
        waitpid(madplay_pid, NULL, 0);
        madplay_pid = -1;
    }
    music_state = MUSIC_STOPPED;
    current_playing[0] = '\0';
    return 0;
}

// 暂停/恢复音乐播放
int pause_resume_music(void) {
    if (madplay_pid > 0) {
        if (music_state == MUSIC_PLAYING) {
            kill(madplay_pid, SIGSTOP);
            music_state = MUSIC_PAUSED;
        } else if (music_state == MUSIC_PAUSED) {
            kill(madplay_pid, SIGCONT);
            music_state = MUSIC_PLAYING;
        }
    }
    return 0;
}

// 获取当前播放状态
MusicState get_music_state(void) {
    if (madplay_pid > 0) {
        int status;
        if (waitpid(madplay_pid, &status, WNOHANG) > 0) {
            madplay_pid = -1;
            music_state = MUSIC_STOPPED;
            current_playing[0] = '\0';
        }
    }
    return music_state;
}

// 播放上一首音乐
int play_previous_music(void) {
    if (music_count == 0) return -1;
    
    current_music = (current_music > 0) ? current_music - 1 : music_count - 1;
    return play_music(music_files[current_music].path);
}

// 播放下一首音乐
int play_next_music(void) {
    if (music_count == 0) return -1;
    
    current_music = (current_music < music_count - 1) ? current_music + 1 : 0;
    return play_music(music_files[current_music].path);
}

// 显示音乐播放器界面
int show_music_ui(void) {
    if (!music_files) {
        music_files = calloc(512, sizeof(MusicFile));
        music_count = get_music_files(music_files, 512);
    }
    
    // 清屏
    for (int i = 0; i < 800 * 480; i++) {
        lcd_ptr[i] = 0xFFFFFF;
    }
    
    // 计算当前页的音乐
    int start_idx = current_page * music_per_page;
    int end_idx = start_idx + music_per_page;
    if (end_idx > music_count) end_idx = music_count;
    
    // 显示音乐列表
    for (int i = start_idx; i < end_idx; i++) {
        int row = (i - start_idx) / 3;
        int col = (i - start_idx) % 3;
        int x = 50 + col * 250;
        int y = 50 + row * 200;
        
        // 显示封面或默认背景
        if (music_files[i].has_cover) {
            display_music_cover(music_files[i].cover_path, x, y, 180, 120);
        } else {
            draw_default_music_bg(x, y, 180, 120);
        }
        
        // 绘制播放状态指示器
        if (strcmp(music_files[i].path, current_playing) == 0) {
            draw_playing_border(x, y, 180, 120);
        }
    }
    
    // 显示控制按钮图标
    lcd_draw_png("/zdata/icon/prev.png", 200, 400);
    lcd_draw_png(get_music_state() == MUSIC_PLAYING ? "/zdata/icon/pause.png" : "/zdata/icon/play.png", 350, 400);
    lcd_draw_png("/zdata/icon/next.png", 500, 400);
    lcd_draw_png("/zdata/icon/exit.png", 700, 400);
    
    return 0;
}

// 处理音乐播放器触摸事件
int handle_music_touch(int x, int y) {
    // 翻页按钮
    if (y < 100) {
        if (x < 100 && current_page > 0) {
            current_page--;
            show_music_ui();
            return 1;
        }
        if (x > 700) {
            int max_page = (music_count + music_per_page - 1) / music_per_page;
            if (current_page < max_page - 1) {
                current_page++;
                show_music_ui();
                return 1;
            }
        }
    }
    
    // 音乐选择区域
    int start_idx = current_page * music_per_page;
    for (int i = 0; i < music_per_page; i++) {
        int row = i / 3;
        int col = i % 3;
        int music_x = 50 + col * 250;
        int music_y = 50 + row * 200;
        
        if (x >= music_x && x < music_x + 180 && y >= music_y && y < music_y + 120) {
            int music_idx = start_idx + i;
            if (music_idx < music_count) {
                current_music = music_idx;
                play_music(music_files[music_idx].path);
                show_music_ui();
                return 1;
            }
        }
    }
    
    // 控制按钮区域
    if (y > 400 && y < 480) {
        if (x >= 200 && x < 300) {
            play_previous_music();
            show_music_ui();
            return 1;
        }
        if (x >= 350 && x < 450) {
            if (get_music_state() == MUSIC_PLAYING) {
                pause_resume_music();
            } else if (get_music_state() == MUSIC_PAUSED) {
                pause_resume_music();
            } else if (music_count > 0) {
                play_music(music_files[current_music].path);
            }
            show_music_ui();
            return 1;
        }
        if (x >= 500 && x < 600) {
            play_next_music();
            show_music_ui();
            return 1;
        }
        if (x >= 700 && x < 800) {
            stop_music();
            return 2;
        }
    }
    
    return 0;
} 